package com.cnebula.openapi.auth.api;

import com.cnebula.openapi.auth.AuthOptions;
import com.cnebula.openapi.auth.provider.LoginProvider;
import com.cnebula.openapi.auth.provider.OAuthProvider;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;

public class AuthAPIVerticle extends AbstractVerticle {

	private LoginProvider loginServiceProvider;
	private OAuthProvider oauthServiceProvider;

	private final AuthOptions options;

	private static final Logger log = LoggerFactory.getLogger(AuthAPIVerticle.class);

	public AuthAPIVerticle(LoginProvider loginServiceProvider, OAuthProvider oauthServiceProvider, AuthOptions options) {
		this.loginServiceProvider = loginServiceProvider;
		this.oauthServiceProvider = oauthServiceProvider;
		this.options = options;
	}

	@Override
	public void start(Future<Void> future) throws Exception {

		Router router = Router.router(vertx);
		
		router.route().handler(CorsHandler.create("*")
			      .allowedMethod(HttpMethod.GET)
			      .allowedMethod(HttpMethod.POST)
			      .allowedHeader("Content-Type"));
		
		router.route("/*").handler(BodyHandler.create());

		router.get("/libraries/oauth2/login").handler(loginServiceProvider::loginProxy4LSP);
		router.get("/vendors/oauth2/login").handler(loginServiceProvider::loginProxy4LSP);
		router.get("/publishers/oauth2/login").handler(loginServiceProvider::loginProxy4LSP);
		router.get("/loginp/code").handler(loginServiceProvider::loginProxy4LSPCallback);

		router.post("/libraries/oauth2/get_access_token").handler(oauthServiceProvider::getAccessToken);
		router.post("/vendors/oauth2/get_access_token").handler(oauthServiceProvider::getAccessToken);
		router.post("/publishers/oauth2/get_access_token").handler(oauthServiceProvider::getAccessToken);

//		JsonObject config = context.config();
//
//		vertx.createHttpServer().requestHandler(router::accept).listen(config.getInteger("http.port", PORT),
//				config.getString("http.address", HOST), result -> {
//					if (result.succeeded()) {
//						future.complete();
//						log.info("AuthAPIVerticle start");
//
//					} else {
//						future.fail(result.cause());
//					}
//
//				});
		
		vertx.createHttpServer().requestHandler(router::accept).listen(
				options.getPort(), 
				options.getHost(), 
				result -> {
					if (result.succeeded()) {
						future.complete();
						log.info("AuthAPIVerticle server start up [http://"+options.getHost()+":"+options.getPort()+"]");

					} else {
						future.fail(result.cause());
					}

				});
	}
}
